package com.joy.zebra.common.push;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JPushUtils {

	private static Log logger = LogFactory.getLog(JPushUtils.class);
	/** 极光推送 AppKey */
	private static final String J_PUSH_APP_KEY = "76c96f57aba78f1786a09c08";
	/** 极光推送 Master Secret */
	private static final String J_PUSH_MASTER_SECRET = "e150e793ce3802d3c4c036c1";

	private static final String J_PUSH_TEST_REG_ID = "191e35f7e09407e7a5b";

	private static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

	/**
	 * 指定用户群体推送（推送主体带 message 信息）
	 *
	 * @param title      标题
	 * @param content    内容
	 * @param regIds     用户 regId 集合
	 * @param jsonObject 附加参数
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/12/30 9:54
	 **/
	public static boolean sendJPush(String title, String content, List<String> regIds, JsonObject jsonObject) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);

		if (jsonObject == null) {
			logger.error("jsonObject不能为空");
			return false;
		}

		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushByRegId(title, content, regIds, jsonObject);

		try {
			//执行推送
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * 指定用户群体推送（不附加 message）
	 *
	 * @param title   标题
	 * @param content 内容
	 * @param regIds  用户 regId 集合
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/12/30 9:54
	 **/
	public static PushResult sendJPush(String title, String content, List<String> regIds) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);
		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushByRegId(title, content, regIds);
		PushResult result = new PushResult();
		try {
			//执行推送
			result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			result = _gson.fromJson(e.getMessage(), PushResult.class);
			result.statusCode = 1;
			logger.info("Got result - " + result);
			return result;
		}
		return result;
	}

	/**
	 * 指定用户推送
	 *
	 * @param title   标题
	 * @param content 内容
	 * @param regId   用户 regId
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/12/30 9:54
	 **/
	public static boolean sendJPush(String title, String content, String regId) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);

		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushByRegId(title, content, regId);

		try {
			//执行推送
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			String message = e.getMessage();
			logger.error("reg_id ==> " + regId + " 出现错误信息：" + message);
			return false;
		}

		return true;
	}

	/**
	 * 执行自定义消息推送 （不弹窗，应用内隐式推送，用于显示应用内【新消息】等标识）
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	public static boolean sendJMessage(String msgContent, String regId, JsonObject jsonObject) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);

		Message message = Message.newBuilder()
				.setMsgContent(msgContent)
				.addExtra("code", 0)
				.addExtra("msg", "success")
				.addExtra("data", jsonObject)
				.build();

		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushMessageByRegIds(regId, message);

		try {
			//执行推送
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 执行自定义消息推送-批量 （不弹窗，应用内隐式推送，用于显示应用内【新消息】等标识）
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2021/06/12 14:33
	 **/
	public static boolean sendJMessage(String msgContent, List<String> regId, JsonObject jsonObject) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);

		Message message = Message.newBuilder()
				.setMsgContent(msgContent)
				.addExtra("code", 0)
				.addExtra("msg", "success")
				.addExtra("data", jsonObject)
				.build();

		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushMessageByRegIds(regId, message);

		try {
			//执行推送
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 执行自定义消息推送-批量 （不弹窗，应用内隐式推送，用于显示应用内【新消息】等标识）
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2021/06/12 14:33
	 **/
	public static boolean sendJMessage(String msgContent, List<String> regId, String content) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);

		Message message = Message.newBuilder()
				.setMsgContent(msgContent)
				.addExtra("code", 0)
				.addExtra("msg", "success")
				.addExtra("data", content)
				.build();

		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushMessageByRegIds(regId, message);

		try {
			//执行推送
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 执行自定义消息推送 （不弹窗，应用内隐式推送，用于显示应用内【新消息】等标识）
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	public static boolean sendJMessage(String msgContent, String regId, String content) {

		ClientConfig config = ClientConfig.getInstance();
		config.setApnsProduction(true);

		Message message = Message.newBuilder()
				.setMsgContent(msgContent)
				.addExtra("code", 0)
				.addExtra("msg", "success")
				.addExtra("data", content)
				.build();

		//构建极光推送 API
		JPushClient jpushClient = new JPushClient(J_PUSH_MASTER_SECRET, J_PUSH_APP_KEY, null, config);
		//构建推送内容
		PushPayload payload = buildPushMessageByRegIds(regId, message);

		try {
			//执行推送
			PushResult result = jpushClient.sendPush(payload);
			logger.info("Got result - " + result);
			jpushClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 执行推送
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	private static PushPayload buildPushByRegId(String title, String content, List<String> regIds, JsonObject jsonObject) {

		Map<String, String> extras = new HashMap<>(1);

		extras.put("data", jsonObject.toString());

		return PushPayload.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(regIds))
				.setNotification(Notification.android(content, title, extras))
				.build();
	}

	/**
	 * 执行推送
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	private static PushPayload buildPushByRegId(String title, String content, List<String> regIds) {

		return PushPayload.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(regIds))
				.setNotification(Notification.newBuilder()
						.addPlatformNotification(IosNotification.newBuilder().setAlert(content).build())
						.addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).setAlert(content).build()).build())
				.build();
	}

	/**
	 * 执行推送
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	private static PushPayload buildPushByRegId(String title, String content, String regId) {

		return PushPayload.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(regId))
				.setNotification(Notification.newBuilder()
						.addPlatformNotification(IosNotification.newBuilder().setAlert(content).build())
						.addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).setAlert(content).build()).build())
				.build();
	}


	/**
	 * 执行自定义消息推送 （不弹窗，应用内隐式推送，用于显示应用内【新消息】等标识）
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	private static PushPayload buildPushMessageByRegIds(String regId, Message message) {

		return PushPayload.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(regId))
				.setMessage(message)
				.build();

	}

	/**
	 * 执行自定义消息推送 - 批量（不弹窗，应用内隐式推送，用于显示应用内【新消息】等标识）
	 *
	 * @return cn.jpush.api.push.model.PushPayload
	 * @author nianhua.jiang
	 * @date 2020/12/29 14:33
	 **/
	private static PushPayload buildPushMessageByRegIds(List<String> regId, Message message) {

		return PushPayload.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(regId))
				.setMessage(message)
				.build();

	}

//	public static void main(String[] args) {
//
//		List<String> stringList = new ArrayList<>();
//		stringList.add("191e35f7e09407e7a5b");
//		sendJPush("快乐斑马", "1234567654321", stringList);
//	}

}
